from django.contrib.auth.models import AbstractUser, UserManager
from django.db import models

# Create your models here.


# class MyUser(AbstractUser):
#     # username = models.CharField(max_length=50, unique=True, primary_key=True)
#     # password = models.CharField(max_length=50)
#     token = models.CharField(max_length=100, null=True, blank=True)
#     REQUIRED_FIELDS = ['password']
from django.db.models import Index
from django.forms import model_to_dict


class AuthUser(AbstractUser):
    avatar = models.ImageField(null=True, blank=True)
    token = models.CharField(max_length=100, null=True)
    is_online = models.BooleanField(default=False)

    def to_json(self):
        j = model_to_dict(self, exclude=('avatar',
                                         'password',
                                         'is_superuser',
                                         'is_staff',
                                         'is_active',
                                         'date_joined',
                                         'groups',
                                         'user_permissions'))
        if self.avatar:
            j['avatar'] = "http://localhost:8000" + self.avatar.url
        else:
            j['avatar'] = ''

        return j

    class Meta:
        db_table = "im_user"
        indexes = [Index(fields=["username"])]


class Image(models.Model):
    image = models.ImageField()


class Message(models.Model):
    id = models.AutoField(primary_key=True)
    sender = models.ForeignKey(AuthUser, on_delete=models.CASCADE, related_name='sender_id')
    receiver = models.ForeignKey(AuthUser, on_delete=models.CASCADE, related_name='receiver_id')
    time = models.DateTimeField(auto_now_add=True)
    msg_type = models.IntegerField(choices=(("1", 1), ("2", 2)), default=1)
    is_read = models.BooleanField(default=False)
    message = models.TextField()

    class Meta:
        db_table = "im_message"
        indexes = [Index(fields=['sender']),
                   Index(fields=['receiver']),
                   Index(fields=['sender', 'receiver'])]
